package com.example.sicnuaccountingapp.ui.transaction

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.sicnuaccountingapp.data.entity.Category
import com.example.sicnuaccountingapp.data.entity.Transaction
import com.example.sicnuaccountingapp.data.entity.TransactionType
import com.example.sicnuaccountingapp.data.repository.CategoryRepository
import com.example.sicnuaccountingapp.data.repository.TransactionRepository
import com.example.sicnuaccountingapp.utils.PreferencesManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AddTransactionViewModel @Inject constructor(
    private val transactionRepository: TransactionRepository,
    private val categoryRepository: CategoryRepository,
    private val preferencesManager: PreferencesManager
) : ViewModel() {

    private val _state = MutableStateFlow<AddTransactionUiState>(AddTransactionUiState.Initial)
    val state: StateFlow<AddTransactionUiState> = _state.asStateFlow()

    private var currentType = TransactionType.EXPENSE
    val categories = MutableStateFlow<List<Category>>(emptyList())

    init {
        loadCategories()
    }

    fun setType(type: TransactionType) {
        currentType = type
        loadCategories()
    }

    private fun loadCategories() {
        viewModelScope.launch {
            try {
                categoryRepository.getCategoriesByType(preferencesManager.userId, currentType)
                    .collect { newCategories ->
                        categories.value = newCategories
                    }
            } catch (e: Exception) {
                _state.value = AddTransactionUiState.Error(e.message ?: "加载分类失败")
            }
        }
    }

    fun addTransaction(amount: Double, categoryId: Long?,categoryName:String?, note: String?) {
        viewModelScope.launch {
            try {
                _state.value = AddTransactionUiState.Loading
                val transaction = Transaction(
                    userId = preferencesManager.userId,
                    amount = amount,
                    categoryId = categoryId,
                    categoryName = categoryName,
                    type = currentType,
                    note = note
                )
                transactionRepository.addTransaction(transaction)
                _state.value = AddTransactionUiState.Success
            } catch (e: Exception) {
                _state.value = AddTransactionUiState.Error(e.message ?: "添加失败")
            }
        }
    }

    fun updateTransaction(transaction: Transaction) {
        viewModelScope.launch {
            try {
                _state.value = AddTransactionUiState.Loading
                transactionRepository.updateTransaction(transaction)
                _state.value = AddTransactionUiState.Success
            } catch (e: Exception) {
                _state.value = AddTransactionUiState.Error(e.message ?: "更新失败")
            }
        }
    }

    fun setUserId(userId: Long) {
        viewModelScope.launch {
            try {
                loadCategories()
            } catch (e: Exception) {
                _state.value = AddTransactionUiState.Error(e.message ?: "加载失败")
            }
        }
    }

    fun deleteTransaction(transaction: Transaction) {
        viewModelScope.launch {
            try {
                _state.value = AddTransactionUiState.Loading
                transactionRepository.deleteTransaction(transaction)
                _state.value = AddTransactionUiState.Success
            } catch (e: Exception) {
                _state.value = AddTransactionUiState.Error(e.message ?: "删除失败")
            }
        }
    }
}